/**
 * @file /src/main_window.cpp
 *
 * @brief Implementation for the qt gui->
 *
 * @date February 2011
 **/
/*****************************************************************************
** Includes
*****************************************************************************/
#include<QDesktopWidget>
#include <QtGui>
#include <QMessageBox>
#include <iostream>
#include "../include/cyrobot_monitor/main_window.hpp"
#include <QFile>
#include <QTime>
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<QDebug>
/*****************************************************************************
** Namespaces
*****************************************************************************/

namespace cyrobot_monitor {

using namespace Qt;

/*****************************************************************************
** Implementation [MainWindow]
*****************************************************************************/

MainWindow::MainWindow(int argc, char** argv, QWidget *parent)
	: QMainWindow(parent),
    ui(new Ui::MainWindowDesign), 
    qnode(argc,argv)
{

    ui->setupUi(this); // Calling this incidentally connects all ui's triggers to on_...() callbacks in this class.
    //QObject::connect(ui->actionAbout_Qt, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt())); // qApp is a global variable for the application
    initUis();
    initData();
    //读取配置文件
    ReadSettings();
    setWindowIcon(QIcon(":/images/icon.png"));
    ui->label_4->setText("Status");
    ui->pushButton_caijilujin->setText("Start"); 
    ui->pushButton_2->setText("Reserved");     
    ui->pushButton_caijilujin_2->setText("End"); 
    ui->pushButton->setText("Choose"); 
    ui->checkBox->setText("rviz");
    ui->pushButton_3->setText("update");
    ui->tab_manager->setCurrentIndex(0); // ensure the first tab is showing - qt-designer should have this already hardwired, but often loses it (settings?).
    ui->groupBox->show();
    ui->tab_manager->show();
    ui->yincang->hide();
    ui->tabWidget->setTabEnabled(1,false);
    ui->tabWidget->setStyleSheet("QTabBar::tab:disabled {width: 0;color: transparent;}");
    //QObject::connect(&qnode, SIGNAL(rosShutdown()), this, SLOT(close()));
    /*********************
    ** Logging
    **********************/    
    //ui->pushButton_3->setEnabled(false);
    addtopic_form = new AddTopics();
    //绑定添加rviz话题信号
    connect(addtopic_form, SIGNAL(Topic_choose(QTreeWidgetItem *, QString)), this, SLOT(slot_choose_topic(QTreeWidgetItem *, QString)));
    connect(&test1,SIGNAL(fasong_csv(int,bool)),this,SLOT(slot_csv_x(int,bool)));
    connect(&test1,SIGNAL(fasong_lujing(int)),this,SLOT(slot_csv_y(int)));
    /*********************
    ** 自动连接master
    **********************/
    if ( ui->checkbox_remember_settings->isChecked() ) {
        on_button_connect_clicked();
    }
    //链接connect
    connections();

}

//析构函数
MainWindow::~MainWindow()
{
    if( base_cmd)
    {
        delete base_cmd;
        base_cmd = nullptr;
    }
    if(map_rviz_)
    {
        delete map_rviz_;
        map_rviz_ = nullptr;
    }
}

//初始化UI
void MainWindow::initUis()
{
   // ui->groupBox_3->setEnabled(false);

    ui->tab_manager->setCurrentIndex(0);
    ui->tabWidget->setCurrentIndex(0);
    
    ui->pushButton_remove_topic->setEnabled(false);
    ui->pushButton_rename_topic->setEnabled(false);


    ui->button_disconnect->setEnabled(false);
}

void MainWindow::initData()
{
    m_mapRvizDisplays.insert("Axes", RVIZ_DISPLAY_AXES);
    m_mapRvizDisplays.insert("Camera", RVIZ_DISPLAY_CAMERA);
    m_mapRvizDisplays.insert("DepthCloud", RVIZ_DISPLAY_DEPTHCLOUD);
    m_mapRvizDisplays.insert("Effort", RVIZ_DISPLAY_EFFORT);
    m_mapRvizDisplays.insert("FluidPressure", RVIZ_DISPLAY_FLUIDPRESSURE);
    m_mapRvizDisplays.insert("Grid", RVIZ_DISPLAY_GRID);
    m_mapRvizDisplays.insert("GridCells", RVIZ_DISPLAY_GRIDCELLS);
    m_mapRvizDisplays.insert("Group", RVIZ_DISPLAY_GROUP);
    m_mapRvizDisplays.insert("Illuminance", RVIZ_DISPLAY_ILLUMINANCE);
    m_mapRvizDisplays.insert("Image", RVIZ_DISPLAY_IMAGE);
    m_mapRvizDisplays.insert("InterativerMarker", RVIZ_DISPLAY_INTERATIVEMARKER);
    m_mapRvizDisplays.insert("LaserScan", RVIZ_DISPLAY_LASERSCAN);
    m_mapRvizDisplays.insert("Map", RVIZ_DISPLAY_MAP);
    m_mapRvizDisplays.insert("Marker", RVIZ_DISPLAY_MARKER);
    m_mapRvizDisplays.insert("MarkerArray", RVIZ_DISPLAY_MARKERARRAY);
    m_mapRvizDisplays.insert("Odometry", RVIZ_DISPLAY_ODOMETRY);
    m_mapRvizDisplays.insert("Path", RVIZ_DISPLAY_PATH);
    m_mapRvizDisplays.insert("PointCloud", RVIZ_DISPLAY_POINTCLOUD);
    m_mapRvizDisplays.insert("PointCloud2", RVIZ_DISPLAY_POINTCLOUD2);
    m_mapRvizDisplays.insert("PointStamped", RVIZ_DISPLAY_POINTSTAMPED);
    m_mapRvizDisplays.insert("Polygon", RVIZ_DISPLAY_POLYGON);
    m_mapRvizDisplays.insert("Pose", RVIZ_DISPLAY_POSE);
    m_mapRvizDisplays.insert("PoseArray", RVIZ_DISPLAY_POSEARRAY);
    m_mapRvizDisplays.insert("PoseWithCovariance", RVIZ_DISPLAY_POSEWITHCOVARIANCE);
    m_mapRvizDisplays.insert("Range", RVIZ_DISPLAY_RANGE);
    m_mapRvizDisplays.insert("RelativeHumidity", RVIZ_DISPLAY_RELATIVEHUMIDITY);
    m_mapRvizDisplays.insert("RobotModel", RVIZ_DISPLAY_ROBOTMODEL);
    m_mapRvizDisplays.insert("TF", RVIZ_DISPLAY_TF);
    m_mapRvizDisplays.insert("Temperature", RVIZ_DISPLAY_TEMPERATURE);
    m_mapRvizDisplays.insert("WrenchStamped", RVIZ_DISPLAY_WRENCHSTAMPED);
}

void MainWindow::initRviz()
{
    ui->label_rvizShow->hide();
    map_rviz_=new QRviz(ui->verticalLayout_build_map,"qrviz");
    connect(map_rviz_, &QRviz::ReturnModelSignal, this, &MainWindow::RvizGetModel);
    map_rviz_->GetDisplayTreeModel();
    QMap<QString, QVariant> namevalue;
    namevalue.insert("Line Style", "Billboards");
    namevalue.insert("Color", QColor(160, 160, 160));
    namevalue.insert("Plane Cell Count", 10);
    map_rviz_->DisplayInit(RVIZ_DISPLAY_GRID, "Grid", true, namevalue);
    
    ui->pushButton_add_topic->setEnabled(true);
    ui->pushButton_rvizReadDisplaySet->setEnabled(true);
    ui->pushButton_rvizSaveDisplaySet->setEnabled(true);
}

void MainWindow::RvizGetModel(QAbstractItemModel *model)
{
    m_modelRvizDisplay = model;
    ui->treeView_rvizDisplayTree->setModel(model);
}

void MainWindow::connections()
{
    QObject::connect(&qnode, SIGNAL(loggingUpdated()), this, SLOT(updateLoggingView()));
    QObject::connect(&qnode, SIGNAL(rosShutdown()), this, SLOT(slot_rosShutdown()));
    QObject::connect(&qnode, SIGNAL(Master_shutdown()), this, SLOT(slot_rosShutdown()));
       //绑定快捷按钮相关函数
    //绑定slider的函数
    //设置界面
      //绑定速度控制按钮
    //设置2D Pose
    connect(ui->set_pos_btn,SIGNAL(clicked()),this,SLOT(slot_set_2D_Pos()));
    //设置2D goal
    connect(ui->set_goal_btn,SIGNAL(clicked()),this,SLOT(slot_set_2D_Goal()));
    //设置MoveCamera
    connect(ui->move_camera_btn,SIGNAL(clicked()),this,SLOT(slot_move_camera_btn()));
    //设置Select
    connect(ui->set_select_btn,SIGNAL(clicked()),this,SLOT(slot_set_select()));
    //设置返航点
    connect(ui->set_return_btn,SIGNAL(clicked()),this,SLOT(slot_set_return_point()));
    //返航
    connect(ui->return_btn,SIGNAL(clicked()),this,SLOT(slot_return_point()));
    //左工具栏tab索引改变
    connect(ui->tab_manager,SIGNAL(currentChanged(int)),this,SLOT(slot_tab_manage_currentChanged(int)));
    //右工具栏索引改变
    connect(ui->tabWidget,SIGNAL(currentChanged(int)),this,SLOT(slot_tab_Widget_currentChanged(int)));
    //刷新话题列表

}
//设置界面
void MainWindow::slot_setting_frame()
{
    if(set != nullptr)
    {
        delete set;
        set=new Settings();
        set->setWindowModality(Qt::ApplicationModal);
        set->show();
    }
    else
    {
        set=new Settings();
        set->setWindowModality(Qt::ApplicationModal);
        set->show();
    }
    //绑定set确认按钮点击事件
}
//刷新当前坐标
void MainWindow::slot_position_change(QString frame,double x,double y,double z,double w)
{
    //更新ui显示
    ui->label_frame->setText(frame);
    ui->label_x->setText(QString::number(x));
    ui->label_y->setText(QString::number(y));
    ui->label_z->setText(QString::number(z));
    ui->label_w->setText(QString::number(w));
}
//刷新返航地点
void MainWindow::slot_set_return_point()
{
    //更新ui返航点显示
    ui->label_return_x->setText(ui->label_x->text());
    ui->label_return_y->setText(ui->label_y->text());
    ui->label_return_z->setText(ui->label_z->text());
    ui->label_return_w->setText(ui->label_w->text());
    //写入setting
    QSettings settings("return-position", "cyrobot_monitor");
    settings.setValue("x",ui->label_x->text());
    settings.setValue("y",ui->label_y->text());
    settings.setValue("z",ui->label_z->text());
    settings.setValue("w",ui->label_w->text());
    //发出声音提醒
    if(media_player!=nullptr)
     {
         delete media_player;
         media_player=nullptr;
     }
     media_player=new QSoundEffect;
     media_player->setSource(QUrl::fromLocalFile("://media/refresh_return.wav"));
     media_player->play();

}
//返航
void MainWindow::slot_return_point()
{
    qnode.set_goal(ui->label_frame->text(),ui->label_return_x->text().toDouble(),ui->label_return_y->text().toDouble(),ui->label_return_z->text().toDouble(),ui->label_return_w->text().toDouble());
    if(media_player!=nullptr)
       {
           delete media_player;
           media_player=nullptr;
       }
       media_player=new QSoundEffect;
       media_player->setSource(QUrl::fromLocalFile("://media/start_return.wav"));
       media_player->play();
}
//设置导航当前位置按钮的槽函数
void MainWindow::slot_set_2D_Pos()
{
 map_rviz_->Set_Pos();
// ui->label_map_msg->setText("请在地图中选择机器人的初始位置");
}
//设置导航目标位置按钮的槽函数
void MainWindow::slot_set_2D_Goal()
{
  map_rviz_->Set_Goal();
//  ui->label_map_msg->setText("请在地图中选择机器人导航的目标位置");
}
void MainWindow::slot_move_camera_btn()
{
    map_rviz_->Set_MoveCamera();
    qDebug()<<"move camera";
}
void MainWindow::slot_set_select()
{
    map_rviz_->Set_Select();
}


//选中要添加的话题的槽函数
void MainWindow::slot_choose_topic(QTreeWidgetItem *choose, QString name)
{
    QString ClassID = choose->text(0);
    // 检查重名
    name = JudgeDisplayNewName(name);
    
    qDebug() << "choose topic ClassID:" << ClassID << ", name:" << name;
    QMap<QString, QVariant> namevalue;
    namevalue.clear();
    map_rviz_->DisplayInit(m_mapRvizDisplays[ClassID], name, true, namevalue);
}

///
/// \brief 检查重名
/// \param name
/// \return 
///
QString MainWindow::JudgeDisplayNewName(QString name)
{
    if (m_modelRvizDisplay != nullptr)
    {
        bool same = true;
        while (same)
        {
            same = false;
            for (int i = 0; i < m_modelRvizDisplay->rowCount(); i++)
            {
                //m_sRvizDisplayChooseName = index.data().value<QString>();
                if (m_modelRvizDisplay->index(i, 0).data().value<QString>() == name)
                {
                    if (name.indexOf("_") != -1)
                    {
                        int num = name.section("_", -1, -1).toInt();
                        name = name.left(name.length() - name.section("_", -1, -1).length() - 1);
                        if (num <= 1)
                        {
                            num = 2;
                        }
                        else
                        {
                            num++;
                        }
                        name = name + "_" + QString::number(num);
                    }
                    else {
                      name = name + "_2";
                    }
                    same = true;
                    break;
                }
            }
        }
    }
    return name;
}

//左工具栏索引改变
void MainWindow::slot_tab_manage_currentChanged(int index)
{
    switch (index) {
    case 0:

        break;
    case 1:

        ui->tabWidget->setCurrentIndex(1);
        break;
    case 2:
        break;

    }
}
//右工具栏索引改变
void MainWindow::slot_tab_Widget_currentChanged(int index)
{
    switch (index) {
    case 0:

        break;
    case 1:
        ui->tab_manager->setCurrentIndex(1);
        break;
    case 2:
        break;

    }
}




/*****************************************************************************
** Implementation [Slots]
*****************************************************************************/

void MainWindow::showNoMasterMessage() {
	QMessageBox msgBox;
	msgBox.setText("Couldn't find the ros master.");
	msgBox.exec();
    close();
}

void MainWindow::inform(QString strdata)
{
    QMessageBox m_r;
    m_r.setWindowTitle("提示");
    m_r.setText(strdata);
    m_r.exec();
}
bool MainWindow::AskInform(QString strdata)
{
    QMessageBox m_r;

    m_r.setWindowTitle("提示");
    m_r.setText(strdata);
    m_r.addButton(tr("确认"), QMessageBox::ActionRole);
    m_r.addButton(tr("取消"), QMessageBox::ActionRole);

    int isok = m_r.exec();
    if (isok == 1)
    {
        return false;
    }
    else
    {
        return true;
    }
}

/*
 * These triggers whenever the button is clicked, regardless of whether it
 * is already checked or not.
 */



//当ros与master的连接断开时
void MainWindow::slot_rosShutdown()
{
    ui->label_robot_staue_img->setPixmap(QPixmap::fromImage(QImage("://images/offline.png")));
     ui->label_statue_text->setStyleSheet("color:red;");
    ui->label_statue_text->setText("离线");
    ui->button_connect->setEnabled(true);
    ui->line_edit_master->setReadOnly(false);
    ui->line_edit_host->setReadOnly(false);
    ui->line_edit_topic->setReadOnly(false);
}

void MainWindow::on_checkbox_use_environment_stateChanged(int state) {
	bool enabled;
	if ( state == 0 ) {
		enabled = true;
	} else {
		enabled = false;
	}
	ui->line_edit_master->setEnabled(enabled);
	ui->line_edit_host->setEnabled(enabled);
	//ui->line_edit_topic->setEnabled(enabled);
}

/*****************************************************************************
** Implemenation [Slots][manually connected]
*****************************************************************************/

/**
 * This function is signalled by the underlying model. When the model changes,
 * this will drop the cursor down to the last line in the QListview to ensure
 * the user can always see the latest log message.
 */


/*****************************************************************************
** Implementation [Menu]
*****************************************************************************/

void MainWindow::on_actionAbout_triggered() {
    //QMessageBox::about(this, tr("About ..."),tr("<h2>PACKAGE_NAME Test Program 0.10</h2><p>Copyright Yujin Robot</p><p>This package needs an about description.</p>"));
}

/*****************************************************************************
** Implementation [Configuration]
*****************************************************************************/

void MainWindow::ReadSettings() {
    QSettings settings("Qt-Ros Package", "cyrobot_rviz_tree");
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
    QString master_url = settings.value("master_url",QString("http://localhost:11311/")).toString();
    QString host_url = settings.value("host_url", QString("localhost")).toString();
    //QString topic_name = settings.value("topic_name", QString("/chatter")).toString();
    ui->line_edit_master->setText(master_url);
    ui->line_edit_host->setText(host_url);
    //ui->line_edit_topic->setText(topic_name);
    bool remember = settings.value("remember_settings", false).toBool();
    ui->checkbox_remember_settings->setChecked(remember);
    bool checked = settings.value("use_environment_variables", false).toBool();
    ui->checkbox_use_environment->setChecked(checked);
    if ( checked ) {
    	ui->line_edit_master->setEnabled(false);
    	ui->line_edit_host->setEnabled(false);
    	//ui->line_edit_topic->setEnabled(false);
    }

    QSettings return_pos("return-position","cyrobot_rviz_tree");
    ui->label_return_x->setText(return_pos.value("x",QString("0")).toString());
    ui->label_return_y->setText(return_pos.value("y",QString("0")).toString());
    ui->label_return_z->setText(return_pos.value("z",QString("0")).toString());
    ui->label_return_w->setText(return_pos.value("w",QString("0")).toString());

    //读取快捷指令的setting
    QSettings quick_setting("quick_setting","cyrobot_rviz_tree");
    QStringList ch_key=quick_setting.childKeys();


}


void MainWindow::closeEvent(QCloseEvent *event)
{

    QMainWindow::closeEvent(event);
}

}  // namespace cyrobot_monitor

///
/// \brief 增加topic
///
void cyrobot_monitor::MainWindow::on_pushButton_add_topic_clicked()
{
    addtopic_form->show();
}

///
/// \brief 删除topic
///
void cyrobot_monitor::MainWindow::on_pushButton_remove_topic_clicked()
{
    if (ui->treeView_rvizDisplayTree->currentIndex().row() >= 0)
    {
        m_sRvizDisplayChooseName_ = ui->treeView_rvizDisplayTree->currentIndex().data().value<QString>();
        map_rviz_->RemoveDisplay(m_sRvizDisplayChooseName_);
        if (ui->treeView_rvizDisplayTree->currentIndex().row() >= 0)
        {
            on_treeView_rvizDisplayTree_clicked(ui->treeView_rvizDisplayTree->currentIndex());
        }
        else
        {
            m_sRvizDisplayChooseName_.clear();
        }
    }
    else
    {
        inform("请选择Display后再执行此操作");
    }
}

///
/// \brief 重命名topic
///
void cyrobot_monitor::MainWindow::on_pushButton_rename_topic_clicked()
{
    if (ui->treeView_rvizDisplayTree->currentIndex().row() < 0)
    {
        inform("请选择Display后再执行此操作");
        return ;
    }
    QString dlgTitle = "重命名";
    QString txtlabel = "请输入名字：";
    QString defaultInupt = m_sRvizDisplayChooseName_;
    QLineEdit::EchoMode echoMode = QLineEdit::Normal;
    bool ok = false;
    QString newname = QInputDialog::getText(this, dlgTitle, txtlabel, echoMode, defaultInupt, &ok);
    if (ok && !newname.isEmpty())
    {
        if (newname != defaultInupt)
        {
            QString nosamename = JudgeDisplayNewName(newname);
            map_rviz_->RenameDisplay(defaultInupt, nosamename);
            m_sRvizDisplayChooseName_ = nosamename;
            if (nosamename != newname)
            {
                inform("命名重复！命名已自动更改为" + nosamename);
            }
        }
    }
    else if (ok)
    {
        inform("输入内容为空，重命名失败");
    }
}

void cyrobot_monitor::MainWindow::on_treeView_rvizDisplayTree_clicked(const QModelIndex &index)
{
    m_sRvizDisplayChooseName_ = index.data().value<QString>();
    if (index.parent().row() == -1)   // Display 的根节点
    {
        if (index.row() > 1)
        {
            ui->pushButton_remove_topic->setEnabled(true);
            ui->pushButton_rename_topic->setEnabled(true);
        }
        else
        {
            ui->pushButton_remove_topic->setEnabled(false);
            ui->pushButton_rename_topic->setEnabled(false);
        }
    }
    else
    {
        ui->pushButton_remove_topic->setEnabled(false);
        ui->pushButton_rename_topic->setEnabled(false);
    }
}

/// \brief 连接ROS
void cyrobot_monitor::MainWindow::on_button_connect_clicked()
{
    //如果使用环境变量
    if ( ui->checkbox_use_environment->isChecked() )
    {
        if ( !qnode.init() )
        {
            //showNoMasterMessage();
            QMessageBox::warning(nullptr, "失败", "连接ROS Master失败！请检查你的网络或连接字符串！", QMessageBox::Yes, QMessageBox::Yes);
            ui->label_robot_staue_img->setPixmap(QPixmap::fromImage(QImage("://images/offline.png")));
            ui->label_statue_text->setStyleSheet("color:red;");
            ui->label_statue_text->setText("离线");
            ui->tab_manager->setTabEnabled(1,false);
            ui->tabWidget->setTabEnabled(1,false);
           // ui->groupBox_3->setEnabled(false);
            return ;
        }
    }
    //如果不使用环境变量
    else
    {
        if ( !qnode.init(ui->line_edit_master->text().toStdString(), ui->line_edit_host->text().toStdString()) )
        {
            QMessageBox::warning(nullptr, "失败", "连接ROS Master失败！请检查你的网络或连接字符串！", QMessageBox::Yes, QMessageBox::Yes);
            ui->label_robot_staue_img->setPixmap(QPixmap::fromImage(QImage("://images/offline.png")));
            ui->label_statue_text->setStyleSheet("color:red;");
            ui->label_statue_text->setText("离线");
            ui->tab_manager->setTabEnabled(1,false);
            ui->tabWidget->setTabEnabled(1,false);
            //ui->groupBox_3->setEnabled(false);
            //showNoMasterMessage();
            return ;
        }
        else
        {
            ui->line_edit_master->setReadOnly(true);
            ui->line_edit_host->setReadOnly(true);
            ui->line_edit_topic->setReadOnly(true);
        }
    }
    ui->tab_manager->setTabEnabled(1,true);
   // ui->tabWidget->setTabEnabled(1,true);
   // ui->groupBox_3->setEnabled(true);
    //初始化rviz
    initRviz();
    map_rviz_->ReadDisplaySet(path1.yaml_path);
    
    
    ui->button_connect->setEnabled(false);
    ui->label_robot_staue_img->setPixmap(QPixmap::fromImage(QImage("://images/online.png")));
    ui->label_statue_text->setStyleSheet("color:green;");
    ui->label_statue_text->setText("在线");
    ui->button_disconnect->setEnabled(true);
    //初始化视频订阅的显示


}

/// \brief 断开ROS
void cyrobot_monitor::MainWindow::on_button_disconnect_clicked()
{
    qnode.disinit();
    map_rviz_->quit();
    delete map_rviz_;
    map_rviz_ = nullptr;
    ui->pushButton_add_topic->setEnabled(false);
    ui->pushButton_remove_topic->setEnabled(false);
    ui->pushButton_rename_topic->setEnabled(false);
    ui->pushButton_rvizReadDisplaySet->setEnabled(false);
    ui->pushButton_rvizSaveDisplaySet->setEnabled(false);
    ui->label_rvizShow->show();
    ui->button_disconnect->setEnabled(false);
    ui->button_connect->setEnabled(true);
    
}

void cyrobot_monitor::MainWindow::on_pushButton_rvizReadDisplaySet_clicked()
{
    if (map_rviz_ == nullptr)
    {
        return;
    }
    QString path = QFileDialog::getOpenFileName(this, "导入 RVIZ Display 配置", "/home/" + getUserName() + "/", "YAML(*.yaml);;ALL(*.*)");
    if (!path.isEmpty())
    {
        map_rviz_->ReadDisplaySet(path);
    }
}

void cyrobot_monitor::MainWindow::on_pushButton_rvizSaveDisplaySet_clicked()
{
    if (map_rviz_ == nullptr)
    {
        return;
    }
    QString path = QFileDialog::getSaveFileName(this, "导出 RVIZ Display 配置", "/home/" + getUserName() + "/", "YAML(*.yaml)");
    
    if (!path.isEmpty())
    {
        if (path.section('/', -1, -1).indexOf('.') < 0)
        {
            path = path + ".yaml";
        }
        map_rviz_->OutDisplaySet(path);
    }
}

QString cyrobot_monitor::MainWindow::getUserName()
{
    QString userPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
    QString userName = userPath.section("/", -1, -1);
    return userName;
}



void cyrobot_monitor::MainWindow::on_pushButton_caijilujin_clicked()
{
      QString maomaomao = QString("gnome-terminal --working-directory=%1 -x ./Trajectory_Saver.sh").arg(path1.Trajectory_Saver_file_path);
      system(maomaomao.toLatin1());
      ui->label_caiji->setAlarm(2);
      QBrush myBrush;
      QPalette paleette;
      myBrush = QBrush(Qt::green,Qt::DiagCrossPattern);
      paleette.setBrush(QPalette::Text,myBrush);
      ui->lineEdit_caijilujin->setPalette(paleette);
      ui->lineEdit_caijilujin->setText("正在采集路径");
      ui->pushButton_caijilujin_2->setEnabled(true);
      ui->pushButton_caijilujin->setEnabled(false);
      timerID = startTimer(40);
}

void cyrobot_monitor::MainWindow::on_pushButton_caijilujin_2_clicked()
{
     ui->label_caiji->setAlarm(1);
     QBrush myBrush;
     QPalette paleette;
     myBrush = QBrush(Qt::red,Qt::DiagCrossPattern);
     paleette.setBrush(QPalette::Text,myBrush);
     ui->lineEdit_caijilujin->setPalette(paleette);
     ui->lineEdit_caijilujin->setText("已经结束路径采集");
     system("gnome-terminal -x rosnode kill --all");
     sleep(100);
     //QString path = QString("/home/l/test_ws/src/common/file/waypoint");
     dir1 = QDir(path1.csv_pos_file_path);
     QStringList filters;
     filters<<QString("*.csv");
     dir1.setFilter(QDir::Files | QDir::NoSymLinks);
     dir1.setNameFilters(filters);
     QChar separator = QChar('/');
     if(!path1.csv_pos_file_path.contains(separator)){
       separator = QChar('\\');
     }
     QChar last_char = path1.csv_pos_file_path.at(path1.csv_pos_file_path.length() - 1);
     if(last_char == separator){
       separator = QChar();
     }

     bool not_has_tsy_trajectory_newest = true;

     for(int i = 0; i < dir1.count(); i++){
         QString filename = dir1[i];
         if(filename==path1.weixin_csv_name){
              not_has_tsy_trajectory_newest = false;
              //ok = file.rename(QString("/home/nvidia/Teemo_ws/src/common/file/waypoint/%1.csv").arg(dir.count()));
          }
     }

     if(!not_has_tsy_trajectory_newest){
       int currentScreenWid = QApplication::desktop()->width();
       int currentScreenHei = QApplication::desktop()->height();
       test1.setWindowTitle("路径文件保存");
       test1.change_name("确认路径保存");
       test1.move(currentScreenWid/2-50,currentScreenHei/2-50);
       test1.setWindowTitle("CSV文件创建");
       test1.show();
     }
    // ui->pushButton_3->setEnabled(true);
}

void cyrobot_monitor::MainWindow::sleep(unsigned int msec){
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while(QTime::currentTime() < dieTime){
      QCoreApplication::processEvents(QEventLoop::AllEvents,100);
    }
}

void cyrobot_monitor::MainWindow::slot_csv_x(int x,bool y){
  QChar separator = QChar('/');
  if(!path1.csv_pos_file_path.contains(separator)){
    separator = QChar('\\');
  }
  QChar last_char = path1.csv_pos_file_path.at(path1.csv_pos_file_path.length() - 1);
  if(last_char == separator){
    separator = QChar();
  }
  QString file_path = path1.csv_pos_file_path+separator+path1.weixin_csv_name;
  QFile file(file_path);
  QFile file1(QString(path1.csv_pos_file_path+separator+"%1.csv").arg(x));
  if(file1.exists()){

    file1.remove();
    ok = file.rename(QString("%2/%1.csv").arg(x).arg(path1.csv_pos_file_path));
  }
  else{
    ok = file.rename(QString("/%2/%1.csv").arg(x).arg(path1.csv_pos_file_path));
  }
  if(ok){
    ui->pushButton_caijilujin_2->setEnabled(false);
    ui->pushButton_caijilujin->setEnabled(true);
    ui->label_caiji->setAlarm(2);
    QBrush myBrush;
    QPalette paleette;
    myBrush = QBrush(Qt::green,Qt::DiagCrossPattern);
    paleette.setBrush(QPalette::Text,myBrush);
    ui->lineEdit_caijilujin->setPalette(paleette);
    ui->lineEdit_caijilujin->setText("已完成路径保存");
   }
}

void cyrobot_monitor::MainWindow::slot_csv_y(int x){
  QFile readFile(path1.waypoint_loader_launch_path);
  readFile.open(QIODevice::ReadOnly);
  qDebug()<<readFile.readAll();
  readFile.close();
  QString one = QString(path1.launch_geshi).arg(x);
    //QFile writeFile("/home/l/test_ws/src/planning/waypoint_maker_test/launch/waypoint_loader.launch");
  //QString maomaomao = QString(path1.waypoint_loader_launch_path);
  QFile writeFile(path1.waypoint_loader_launch_path);
  if(writeFile.open(QIODevice::WriteOnly))
  {
          QTextStream stream(&writeFile);
          stream<<one;
  }
  writeFile.close();
}


void cyrobot_monitor::MainWindow::on_pushButton_clicked()
{
  int currentScreenWid = QApplication::desktop()->width();
  int currentScreenHei = QApplication::desktop()->height();

  test1.move(currentScreenWid/2-50,currentScreenHei/2-50);
  test1.setWindowTitle("路径选取");
  test1.change_name("确认路径选取");
  test1.show();
}


void cyrobot_monitor::MainWindow::timerEvent(QTimerEvent *event){
  if(event->timerId() == timerID){
    QFile file(path1.csv_file_path);
    if(file.exists()){
      ui->label_caiji->setAlarm(2);
      QBrush myBrush;
      QPalette paleette;
      myBrush = QBrush(Qt::green,Qt::DiagCrossPattern);
      paleette.setBrush(QPalette::Text,myBrush);
      ui->lineEdit_caijilujin->setPalette(paleette);
      ui->lineEdit_caijilujin->setText("可以开始进行路径采集");
      killTimer(timerID);
    }
    else{
      ui->label_caiji->setAlarm(1);
      QBrush myBrush;
      QPalette paleette;
      myBrush = QBrush(Qt::red,Qt::DiagCrossPattern);
      paleette.setBrush(QPalette::Text,myBrush);
      ui->lineEdit_caijilujin->setPalette(paleette);
      ui->lineEdit_caijilujin->setText("卫星信号接受中");
    }
  }
  if(event->timerId() == timerID1){

    ui->pushButton_3->setEnabled(true);
    killTimer(timerID1);
  }

}

void cyrobot_monitor::MainWindow::on_pushButton_2_clicked()
{
  system("gnome-terminal -x rosnode kill --all");
  sleep(200);
  system("gnome-terminal --working-directory=/home/nvidia/test_ws/src/run -x ./reserved.sh");
}

void cyrobot_monitor::MainWindow::on_checkBox_clicked()
{
    bool status = ui->checkBox->isChecked();
    if(status==true){
      ui->tabWidget->setTabEnabled(1,true);
      ui->tabWidget->setStyleSheet("QTabBar::tab:enabled {width: 75}");
    }
    else{
      ui->tabWidget->setTabEnabled(1,false);
      ui->tabWidget->setStyleSheet("QTabBar::tab:disabled {width: 0;color: transparent;}");

    }
}

void cyrobot_monitor::MainWindow::on_button_connect_pressed()
{
    ui->button_connect->setStyleSheet("background-color:rgb(20,68,106)");
}

void cyrobot_monitor::MainWindow::on_button_connect_released()
{
    ui->button_connect->setStyleSheet("");
}

void cyrobot_monitor::MainWindow::on_pushButton_caijilujin_pressed()
{
    ui->pushButton_caijilujin->setStyleSheet("background-color:rgb(20,68,106)");
}

void cyrobot_monitor::MainWindow::on_pushButton_caijilujin_released()
{
    ui->pushButton_caijilujin->setStyleSheet("");
}

void cyrobot_monitor::MainWindow::on_pushButton_caijilujin_2_pressed()
{
    ui->pushButton_caijilujin_2->setStyleSheet("background-color:rgb(20,68,106)");
}

void cyrobot_monitor::MainWindow::on_pushButton_caijilujin_2_released()
{
    ui->pushButton_caijilujin_2->setStyleSheet("");
}

void cyrobot_monitor::MainWindow::on_pushButton_pressed()
{
    ui->pushButton->setStyleSheet("background-color:rgb(20,68,106)");
}

void cyrobot_monitor::MainWindow::on_pushButton_released()
{
    ui->pushButton->setStyleSheet("");
}

void cyrobot_monitor::MainWindow::on_pushButton_2_pressed()
{
    ui->pushButton_2->setStyleSheet("background-color:rgb(20,68,106)");
}

void cyrobot_monitor::MainWindow::on_pushButton_2_released()
{
    ui->pushButton_2->setStyleSheet("");
}

void cyrobot_monitor::MainWindow::on_pushButton_3_clicked()
{
      //on_button_connect_clicked();
       qnode.init(ui->line_edit_master->text().toStdString(), ui->line_edit_host->text().toStdString());
       map_rviz_->ReadDisplaySet(path1.yaml_path);
       timerID1=startTimer(5000);
       ui->pushButton_3->setEnabled(false);
}

void cyrobot_monitor::MainWindow::on_pushButton_3_pressed()
{
    ui->pushButton_3->setStyleSheet("background-color:rgb(20,68,106)");
}

void cyrobot_monitor::MainWindow::on_pushButton_3_released()
{
     ui->pushButton_3->setStyleSheet("");

}
